/* vim: set ts=2 et sw=2 cindent fo=qroca: */

package com.globant.google.mendoza.malbec.transport;

import java.util.Properties;

import javax.xml.bind.JAXBElement;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.globant.google.mendoza.malbec.CalculationListener;
import com.globant.google.mendoza.malbec.CartUtils;
import com.globant.google.mendoza.malbec.OrderListener;

/** This class implements the un-marshalling of notification messages from the
 * GBuy server to the OrderListener implementation.
 *
 * The notification dispatcher must be registered in the transport as a
 * receiver. When a message arrives it unmarshalls the parameters and calls the
 * corresponding method in the OrderListener.
 */
public final class NotificationDispatcher implements Receiver {

  /** The class logger.
   */
  private static Log log = LogFactory.getLog(NotificationDispatcher.class);

  /** The object that receives the order events.
   */
  private OrderListener orderListener;

  /** The object that receives the calculation callback events.
   */
  private CalculationListener calculationListener;

  /** The transport implementation.
   */
  private Transport transport;

  /** Constructs a notification dispatcher.
   *
   * @param theTransport The transport implementation. It cannot be null.
   *
   * @param theOrderListener The object that receives the GBuy messages. If
   * null, theCalculationListener cannot be null.
   *
   * @param theCalculationListener The object that receives the GBuy
   * calculation callback. If null, theOrderListener cannot be null.
   */
  public NotificationDispatcher(final Transport theTransport, final
      OrderListener theOrderListener, final CalculationListener
      theCalculationListener) {
    if (theTransport == null) {
      throw new IllegalArgumentException("the transport cannot be null");
    }
    if (theOrderListener == null && theCalculationListener == null) {
      throw new IllegalArgumentException("The order listener and the"
          + " calculation listener cannot be both null");
    }
    orderListener = theOrderListener;
    calculationListener = theCalculationListener;
    transport = theTransport;
  }

  /** The function called by the transport when a new message is received.
   *
   * If the message is related to an order it returns the GBuy specified
   * acknowledge, and leaves the received callback to process the message. If
   * it is the merchant-calculation-callback, it process the messae in this
   * function and returns the result of the merchant calculation.
   *
   * @param message The received message.
   *
   * @return Returns the GBuy defined acknowledge message.
   */
  public String receive(final String uri, final String method, final Properties
      header, final Properties parameters, final String message) {
    log.trace("Entering receive");

    String answer = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      + "<notification-acknowledgment"
      + " xmlns=\"http://checkout.google.com/schema/2\"/>\n";

    JAXBElement node = CartUtils.unmarshal(message);

    NotificationFirerer firerer = (NotificationFirerer) node.getValue();
    Object response = firerer.preNotify(transport, orderListener,
        calculationListener);
    if (response != null) {
      if (response instanceof JAXBElement) {
        answer = CartUtils.marshal((JAXBElement) response);
      } else if (response instanceof String) {
        answer = (String) response;
        } else {
          throw new RuntimeException("Unexpected response, expected String or "
            + "JAXBElement but " + response.getClass().getName() + " found");
        }
    }
    log.trace("Leaving receive");
    return answer;
  }

  /** Receives the post processing message event.
   *
   * This function returns immediately if the orderListener has not been set.
   *
   * @param message The received message.
   */
  public void received(final String message) {
    log.trace("Entering received");
    if (orderListener == null) {
      return;
    }
    JAXBElement node = CartUtils.unmarshal(message);
    NotificationFirerer firerer = (NotificationFirerer) node.getValue();
    firerer.notify(transport, orderListener);
  }
}

